package cn.yunhe.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.yunhe.controller.UserController;
import cn.yunhe.entity.Listuser;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Repository
public class UserUpLoad extends ActionSupport implements ModelDriven<Object> {

	private static final long serialVersionUID = 1L;
	private static Logger logger = LogManager.getLogger(UserUpLoad.class);
	
	@Autowired
	private UserController uc;
	/**
	 * 用户名
	 */
	private String username;
	
	/**
	 * 用户密码
	 */
	private String userpwd;
	/**
	 * 要保存的头像图片
	 */
	private File head;
	
	/**
	 * 文件的名字  xxx.jpg
	 */
	private String headFileName;
	
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getUserpwd() {
		return userpwd;
	}
	public void setUserpwd(String userpwd) {
		this.userpwd = userpwd;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public File getHead() {
		return head;
	}
	public void setHead(File head) {
		this.head = head;
	}
	public String getHeadFileName() {
		return headFileName;
	}
	public void setHeadFileName(String headFileName) {
		this.headFileName = headFileName;
	}



	public String adduser() throws IOException{
		//要保存到的那个文件夹
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		//输入输出流
        InputStream is = new FileInputStream(head);
        OutputStream os = new FileOutputStream(new File(path, headFileName));
        //写入（保存）
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = is.read(buffer))!=-1){
            os.write(buffer,0,len);
        }
        Listuser user=new Listuser();
        user.setUsername(username);
        user.setUserpwd(userpwd);
        user.setUserimage("/upload/"+headFileName);//保存相对路径
        os.close();
        is.close();
        //是否保存成功
        if(uc.adduser(user)>0){
        	logger.info("添加角色成功");
        	return "success";
        }else{
        	logger.info("添加角色失败");
        	return "fail";
        }
	}
	
	public Object getModel() {
		return null;
	}
	
	
}
